package com.hzit.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.hzit.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.HandlerResultHandlerSupport;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Configuration
public class GatewaySentinelConfig {

	@PostConstruct
	public void init() {
		GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
			@Override
			public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
				// 写法一：
				//  Map map = new HashMap();
				//  map.put("code",0);
				//  map.put("message","接口被限流了");
				// return ServerResponse.status(HttpStatus.OK)
				// 		             .contentType(MediaType.APPLICATION_JSON_UTF8)
				// 					 .body(BodyInserters.fromObject(map),String.class);
				// 写法二：
				R error = R.error(500, "出现了网关限流异常！");
				Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(JSON.toJSONString(error)), String.class);
				return body;
			}
		});
	}
}
